<template>
  <div class="mall-cart-container">
    <div class="cart-header">
      <div class="cart-header-content">
        <p>
          <i class="el-icon-shopping-cart-full" style="color: #ff6700;font-weight: 600"></i>
          我的购物车
        </p>
        <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
      </div>
    </div>
    <div v-if="cartList.length !== 0" class="cart-content">
      <el-table :data="cartList" @selection-change="handleSelectionChange" ref="multipleTable" tooltip-effect="dark">
        <el-table-column type="selection"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <router-link :to="{path: '/item/details',query: { id: scope.row.item.id }}">
              <el-image :src="getImageUrl(scope.row.item.imageUrl)" style="height: 100px; width: 100px"/>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <router-link :to="{path: '/item/details',query: { id: scope.row.item.id }}">
              {{ scope.row.item.name }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="单价">
          <template slot-scope="scope">
            {{ scope.row.item.salePrice }} 元
          </template>
        </el-table-column>
        <el-table-column prop="address" label="数量" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.itemCount" @change="updateCart($event, scope.row)" :min="1" size="small">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="小计" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.item.salePrice * scope.row.itemCount }} 元
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-popover placement="right">
              <p>确定删除吗？</p>
              <div style="text-align: right; margin: 10px 0 0">
                <el-button @click="deleteItem(scope.$index, scope.row.id)" type="primary" size="mini">
                  确定
                </el-button>
              </div>
              <i class="el-icon-error" slot="reference" style="font-size: 18px"></i>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="cart-bar">
        <div class="cart-bar-left">
          <span>
            <router-link to="/item">继续购物</router-link>
          </span>
          <span style="color: #eee; margin: 0 20px">|</span>
          <span class="cart-total">共
            <span class="cart-total-num">{{ cartCount }}</span> 件商品，已选择
            <span class="cart-total-num">{{ checkCount }}</span> 件
          </span>
        </div>
        <div class="cart-bar-right">
          <span>
            <span class="total-price-title">合计：</span>
            <span class="total-price">{{ totalPrice }}元</span>
          </span>
          <el-button @click="addOrder" :disabled="checkCount === 0" v-loading.fullscreen.lock="fullscreenLoading" type="warning" class="btn-primary">
            去结算
          </el-button>
        </div>
      </div>
    </div>
    <MallEmpty title="您的购物车还是空的！" v-else></MallEmpty>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import MallEmpty from '@/components/MallEmpty'
import { mixin } from '../mixins'
import { SPACE, insert, update, selectListByForeignId, deleteByIds } from '../api/baseApi'
export default {
  mixins: [mixin],
  components: {
    MallEmpty
  },
  data() {
    return {
      checkCount: 0,
      totalPrice: 0,
      cartList: [],
      checkList: [],
      fullscreenLoading: false
    }
  },
  watch: {
    checkList: {
      handler(newValue) {
        this.totalPrice = newValue.length === 0 ? 0 : newValue.map(item => item.itemCount * item.item.salePrice).reduce((pre, current) => pre + current)
        this.$store.commit('setCheckList', newValue)
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters({
      cartCount: 'getCartCount'
    })
  },
  activated() {
    this.findCart()
  },
  methods: {
    ...mapActions(['setCartCount']),
    ...mapGetters(['getUser', 'getCartCount']),
    handleSelectionChange(list) {
      this.checkList = list
      this.checkCount = list.length === 0 ? 0 : list.map(item => item.itemCount).reduce((pre, current) => pre + current)
    },
    // 增加订单
    addOrder() {
      if (this.checkList.length === 0) {
        this.showError('没有选中商品')
        return
      }
      this.fullscreenLoading = true
      insert(SPACE.order, this.checkList).then(res => {
        if (res.state === 200) {
          setTimeout(() => {
            deleteByIds(SPACE.cart, this.checkList.map(cart => {
              return cart.id
            }))
            this.setCartCount(this.getCartCount() - this.checkList.length)
            this.$router.push({ path: '/order/confirm', query: { id: res.data.id } })
            this.fullscreenLoading = false
          }, 500)
        }
      })
    },
    // 删除购物车中商品
    deleteItem(index, cartId) {
      deleteByIds(SPACE.cart, [cartId]).then(res => {
        if (res.state === 200) {
          this.cartList.splice(index, 1)
          this.setCartCount(this.getCartCount() - 1)
          this.showSuccess()
        } else this.showError()
      })
    },
    // 修改商品数量
    updateCart(currentCount, cart) {
      console.log('currentCount: ' + currentCount)
      cart.itemCount = currentCount
      update(SPACE.cart, cart)
    },
    // 查询某用户的购物车
    async findCart() {
      selectListByForeignId(SPACE.cart, this.getUser().id).then(res => {
        this.cartList = res.state === 200 ? res.data : []
      })
    }
  }
}
</script>
<style scoped>
.mall-cart-container {
  background-color: #f5f5f5;
  padding-bottom: 20px;
}
.mall-cart-container .cart-header {
  height: 64px;
  border-bottom: 2px solid #ff6700;
  background-color: #fff;
  margin-bottom: 20px;
}
.mall-cart-container .cart-header .cart-header-content {
  width: 1225px;
  margin: 0 auto;
}
.mall-cart-container .cart-header p {
  font-size: 28px;
  line-height: 58px;
  float: left;
  font-weight: normal;
  color: #424242;
}
.mall-cart-container .cart-header span {
  color: #757575;
  font-size: 12px;
  float: left;
  height: 20px;
  line-height: 20px;
  margin-top: 30px;
  margin-left: 15px;
}
.cart-content {
  margin: 0 auto;
  width: 1225px;
}
.cart-content .cart-table-header {
  background-color: #333;
}
.cart-content .el-icon-error:hover {
  cursor: pointer;
  color: #f25807;
}
.mall-cart-container .cart-content .cart-bar {
  height: 50px;
  line-height: 50px;
  background-color: #fff;
}
.mall-cart-container .cart-bar .cart-bar-left {
  float: left;
}
.mall-cart-container .cart-bar .cart-bar-left a {
  line-height: 50px;
  margin-left: 32px;
  color: #757575;
}
.mall-cart-container .cart-bar .cart-bar-left a:hover {
  color: #ff6700;
}
.mall-cart-container .cart-bar .cart-bar-left .cart-total {
  color: #757575;
}
.mall-cart-container .cart-bar .cart-bar-left .cart-total-num {
  color: #ff6700;
}
.mall-cart-container .cart-bar .cart-bar-right {
  float: right;
}
.mall-cart-container .cart-bar .cart-bar-right .total-price-title {
  color: #ff6700;
  font-size: 14px;
}
.mall-cart-container .cart-bar .cart-bar-right .total-price {
  color: #ff6700;
  font-size: 30px;
}
.mall-cart-container .cart-bar .cart-bar-right .btn-primary {
  float: right;
  width: 200px;
  text-align: center;
  font-size: 18px;
  margin-left: 50px;
  height: 50px;
  border-radius: 0;
  border: 0;
  color: #fff;
}
</style>
